import React, { useEffect, useRef, useState } from 'react'
import { getBlogList } from '@/api'
import BlogList from '@/components/blogList'
import BackTop from '@/components/backTop'
import InfiniteScroll from 'react-infinite-scroll-component'
import { showTime } from '@/utils/utils'
import { Empty, Spin } from 'antd'
import store from '@/utils/store'
import style from './index.module.scss'
export default function Index({ history }: any) {
  const [isChangeScrollY, setIsChangeScrollY] = useState(true)
  const [blogList, setBlogList] = useState<BlogList[]>([])
  const [pageNum, setPageNum] = useState(0)
  const [hasMore, setHasMore] = useState(true)
  const container = useRef<HTMLDivElement | null>(null)
  const getBlogListData = async () => {
    try {
      const { data } = await getBlogList({ pageNum, size: 10 })
      if (!data.length || pageNum >= 3) {
        setHasMore(false)
      } else {
        data.forEach((el: BlogList) => {
          el.creatTime = showTime(el.creationTime)
        })
        setPageNum(pageNum + 1)
        setBlogList([...blogList, ...data])
      }
    } catch (err) {}
  }
  const toDetail = (id: number) => {
    store.indexScrollHeight = (container.current as HTMLDivElement).scrollTop
    history.push(`/detail/${id}`)
  }

  useEffect(() => {
    if (blogList.length === 0 || !isChangeScrollY) return
    ;(container.current as HTMLDivElement).scrollTop = store.indexScrollHeight
    setIsChangeScrollY(false)
  }, [blogList, isChangeScrollY, container])
  useEffect(() => {
    getBlogListData()
  }, []) // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <div id="indexContainer" ref={container}>
      <InfiniteScroll
        style={{ overflow: 'visible' }}
        dataLength={blogList.length}
        next={getBlogListData}
        hasMore={hasMore}
        scrollableTarget="indexContainer"
        loader={
          <div className={style.loader}>
            <Spin />
          </div>
        }
        endMessage={<p className={style.no_more}>没有更多了...</p>}
      >
        {blogList.length ? (
          blogList.map((el) => {
            return (
              <div key={el.blogId} onClick={() => toDetail(el.blogId)}>
                <BlogList list={el}></BlogList>
              </div>
            )
          })
        ) : (
          <Empty />
        )}
      </InfiniteScroll>
      <BackTop target={() => document.querySelector('#indexContainer')} />
    </div>
  )
}
